package cn.kent.nio.selector;

import cn.kent.nio.byteBuffer.util.ByteBufferUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * selector 模式实现
 * 读事件
 * - 问题：消息边界，断开处理，ByteBuffer大小处理(动态扩容)
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 创建selector
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false); // 非阻塞模式
        // 创建Selector和Channel的联系(注册)
        SelectionKey sscKey = ssc.register(selector, 0, null);
        // key只关注accept事件（总共四种事件，可以通过参数指定）
        sscKey.interestOps(SelectionKey.OP_ACCEPT);
        log.debug("register key:{}", sscKey);
        ssc.bind(new InetSocketAddress(8080));
        while (true) {
            // 3. select方法，没有事件发生，线程阻塞，有事件发生，线程才会恢复运行
            // 事件发生后，要不处理，要不取消，不能不处理，否则变成了非阻塞模式，cpu飙升。
            selector.select();
            // 4. 处理事件,selectedKeys 内部包含了所有发生的事件
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 处理完的key需要删掉
                iterator.remove();
                log.debug("key: {}", key);
                // 5. 区分事件类型
                if (key.isAcceptable()) { // accept 事件
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel sc = channel.accept();
                    sc.configureBlocking(false);
                    ByteBuffer buffer = ByteBuffer.allocate(16);
                    SelectionKey scKey = sc.register(selector, 0, buffer); // 对每个sc绑定一个buffer
                    scKey.interestOps(SelectionKey.OP_READ);
                    log.debug("socketChannel: {}", sc);
                } else if (key.isReadable()) { // read 事件
                    try {
                        SocketChannel channel = (SocketChannel) key.channel(); // 拿到触发事件的channel
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer); // 如果是正常断开，那么read方法的返回值是-1
                        if (read == -1) {
                            key.cancel();
                        } else {
                            split(buffer);
                            if (buffer.limit() == buffer.position()) {
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        key.cancel(); // 因为客户端已经断开，从selector的keys集合中真正删除key
                    }
                }

                // 取消事件
//                key.cancel();
            }
        }
    }

    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position(); // 保留 \n 字符
                ByteBuffer target = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    target.put(source.get());
                }
                ByteBufferUtil.debugAll(target);
            }
        }
        source.compact();
    }
}
